package com.diaohw.platform.common.util;

import cn.hutool.core.util.ClassUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 刁海文
 * @since 2024/1/14 19:07
 */
public class ClassUtils extends ClassUtil {

    public static <T> Set<Class<T>> children(Class<T> clazz, String basePackage) {
        Set<Class<T>> collect = ClassUtil.scanPackage(basePackage).stream()
                .filter(clazz::isAssignableFrom)
                .map(c -> (Class<T>) c)
                .collect(Collectors.toSet());
        collect.remove(clazz);


        return collect;
    }

    public static <T> Set<Class<T>> children(Class<T> clazz) {
        return children(clazz, "com.diaohw");
    }

    public static <T> T newInstance(Class<T> clazz) {
        try {
            return clazz.getDeclaredConstructor().newInstance();
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException |
                 InstantiationException e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> T methodInvoke(Object clazz, Method method) {
        try {
            Object invoke = method.invoke(clazz);
            return (T) invoke;
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
